package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFarmSystem;
import com.digitalchina.lxnsy.api.BusinessShareFarm;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PayVO;
import com.digitalchina.lxnsy.entity.ShareOrderVO;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.wxapi.WXPayEntryActivity;
import com.facebook.drawee.view.SimpleDraweeView;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/8/8 10:28
 * 修改备注：
 * ================================================
 */
public class ShareOrderDetailsActivity extends BaseActivity {

    @Bind(R.id.order_details_order_number)
    TextView orderDetailsOrderNumber; // 订单号
    @Bind(R.id.order_details_order_date)
    TextView orderDetailsOrderDate; // 日期
    @Bind(R.id.order_details_logistics_name)
    TextView orderDetailsLogisticsName; // 物流公司
    @Bind(R.id.order_details_logistics_number)
    TextView orderDetailsLogisticsNumber; // 快递号
    @Bind(R.id.order_details_person_name)
    TextView orderDetailsPersonName; // 收货人
    @Bind(R.id.order_details_person_mobile)
    TextView orderDetailsPersonMobile; // 联系电话
    @Bind(R.id.order_details_show_address)
    TextView orderDetailsShowAddress; // 地址
    @Bind(R.id.activity_order_details_ll_layout)
    LinearLayout activityOrderDetailsLlLayout; // 商品容器layout
    @Bind(R.id.order_details_goods_total_price)
    TextView orderDetailsGoodsTotalPrice; // 实付款
    @Bind(R.id.order_details_goods_total_freight_price)
    TextView orderDetailsGoodsTotalFreightPrice; // 邮费 格式 "（含运费10元）"
    @Bind(R.id.order_details_total_goods_num)
    TextView orderDetailsTotalGoodsNum; // 商品数量  格式 "共2件商品"
    @Bind(R.id.order_details_seller_name)
    TextView orderDetailsSellerName; // 商家名称
    @Bind(R.id.order_details_seller_logo)
    SimpleDraweeView orderDetailsSellerLogo; // 商家logo
    @Bind(R.id.order_details_seller_phone)
    TextView orderDetailsSellerPhone; // 商家电话


    @Bind(R.id.order_details_btn_left)
    Button orderDetailsBtnLeft; // 左按钮
    @Bind(R.id.order_details_btn_right)
    Button orderDetailsBtnRight; // 右按钮
    @Bind(R.id.order_details_order_operation_layout)
    RelativeLayout orderDetailsOrderOperationLayout;
    @Bind(R.id.order_details_order_status)
    TextView orderDetailsOrderStatus;
    @Bind(R.id.order_details_day)
    TextView orderDetailsDay;
    @Bind(R.id.order_details_order_status_layout)
    LinearLayout orderDetailsOrderStatusLayout;
    @Bind(R.id.order_details_take_goods_code)
    TextView orderDetailsTakeGoodsCode;
    @Bind(R.id.order_details_show_take_goods_code)
    TextView orderDetailsShowTakeGoodsCode;
    @Bind(R.id.order_details_take_goods_code_layout)
    LinearLayout orderDetailsTakeGoodsCodeLayout;
    @Bind(R.id.order_details_take_goods_date)
    TextView orderDetailsTakeGoodsDate;
    @Bind(R.id.order_details_tips)
    TextView orderDetailsTips;
    @Bind(R.id.order_details_logistics_layout)
    LinearLayout orderDetailsLogisticsLayout;
    @Bind(R.id.order_details_logistics_cut_view)
    View orderDetailsLogisticsCutView;
    @Bind(R.id.order_details_person_info)
    LinearLayout orderDetailsPersonInfo;
    @Bind(R.id.order_details_address)
    LinearLayout orderDetailsAddress;
    @Bind(R.id.order_details_address_layout)
    LinearLayout orderDetailsAddressLayout;
    @Bind(R.id.order_details_address_cut_view)
    View orderDetailsAddressCutView;
    @Bind(R.id.order_details_goods_total_price_tag)
    TextView orderDetailsGoodsTotalPriceTag;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.tv_msg)
    TextView tvMsg;
    @Bind(R.id.textView3)
    TextView textView3;
    @Bind(R.id.iv_seller_name_right_arrow)
    ImageView ivSellerNameRightArrow;
    @Bind(R.id.order_details_rl_seller_layout)
    RelativeLayout orderDetailsRlSellerLayout;
    @Bind(R.id.iv_pay_type_right_arrow)
    ImageView ivPayTypeRightArrow;
    @Bind(R.id.order_details_pay_type)
    TextView orderDetailsPayType;
    @Bind(R.id.order_details_pay_type_layout)
    RelativeLayout orderDetailsPayTypeLayout;
    @Bind(R.id.take_address)
    TextView takeAddress;
    @Bind(R.id.iv_take_address_right_arrow)
    ImageView ivTakeAddressRightArrow;
    @Bind(R.id.order_details_take_address)
    TextView orderDetailsTakeAddress;
    @Bind(R.id.order_details_take_address_layout)
    RelativeLayout orderDetailsTakeAddressLayout;
    @Bind(R.id.iv_take_phone_right_arrow)
    ImageView ivTakePhoneRightArrow;
    @Bind(R.id.order_details_take_phone)
    TextView orderDetailsTakePhone;
    @Bind(R.id.order_details_take_phone_layout)
    RelativeLayout orderDetailsTakePhoneLayout;
    @Bind(R.id.iv_take_process_right_arrow)
    ImageView ivTakeProcessRightArrow;
    @Bind(R.id.order_details_take_process)
    TextView orderDetailsTakeProcess;
    @Bind(R.id.order_details_take_goods_process)
    RelativeLayout orderDetailsTakeGoodsProcess;
    @Bind(R.id.order_details_order_total_price)
    TextView orderDetailsOrderTotalPrice;
    @Bind(R.id.order_details_postage_price)
    TextView orderDetailsPostagePrice;
    @Bind(R.id.order_details_order_pay_price)
    TextView orderDetailsOrderPayPrice;
    @Bind(R.id.order_details_order_pay_price_RMB)
    TextView orderDetailsOrderPayPriceRMB;
    @Bind(R.id.tv_address_tip)
    TextView tvAddressTip;


    private ShareOrderVO vo;
    private String beFrom = "";


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_share_order_details);
        setTitle("订单详情");
    }

    @Override
    public void initMember() {
        vo = (ShareOrderVO) getIntent().getSerializableExtra("ShareOrderVO");
        beFrom = getIntent().getSerializableExtra("beFrom").toString();
        setView();
    }

    /**
     * 设置视图
     */
    private void setView() {
        // 订单号
        orderDetailsOrderNumber.setText("订单号：" + vo.getOrderNo());
        // 日期
        orderDetailsOrderDate.setText(vo.getCreateTime());
        if (vo.getLogistics() != null) {
            // 物流公司
            orderDetailsLogisticsName.setText(vo.getLogistics().getDeliveryCorp());
            // 快递号
            orderDetailsLogisticsNumber.setText(vo.getLogistics().getTrackingNo());
        } else {
            // 物流公司
            orderDetailsLogisticsName.setText("暂无");
            // 快递号
            orderDetailsLogisticsNumber.setText("暂无");
        }

        // 地址  1-自提  2-邮寄
        if (vo.getShippingType().equals("1")) {
            tvAddressTip.setText("自提地址");
            orderDetailsPersonInfo.setVisibility(View.GONE);
            orderDetailsLogisticsLayout.setVisibility(View.GONE);
            orderDetailsShowAddress.setText(vo.getPickupAddress());
        } else {
            tvAddressTip.setText("收货地址");
            // 收货人
            orderDetailsPersonName.setText(vo.getConsignee());
            // 联系电话
            orderDetailsPersonMobile.setText(vo.getShippingPhone());
            orderDetailsPersonInfo.setVisibility(View.VISIBLE);
            orderDetailsShowAddress.setText(vo.getShippingAddress());
        }

        // 商品总价
        orderDetailsGoodsTotalPrice.setText(vo.getTotalPriceReal() + "");
        // 商品总价
        orderDetailsGoodsTotalFreightPrice.setText("（含运费" + vo.getFreightPriceReal() + "元）");
        // 商品数量
        int num = 0;
        if (vo.getOrderItems() != null) {
            num = vo.getOrderItems().size();
            activityOrderDetailsLlLayout.removeAllViews();
            for (int i = 0; i < num; i++) {
                View goodsLayout = LayoutInflater.from(this).inflate(R.layout.item_goods, null);

                SimpleDraweeView goodsPic = (SimpleDraweeView) goodsLayout.findViewById(R.id.item_goods_iv_picture);
                TextView goodsName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_name);
                TextView goodsPrice = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_price);
                TextView goodsNum = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_num);
                TextView attrName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_attrName);

                attrName.setText(vo.getOrderItems().get(i).getAttrName() != null ? vo.getOrderItems().get(i).getAttrName() : "无属性");
                goodsName.setText(vo.getOrderItems().get(i).getProductName());

                FrescoUtil.showImageSmall(vo.getOrderItems().get(i).getProductImg(), goodsPic);
                goodsPrice.setText(String.format("￥ %s", vo.getOrderItems().get(i).getPrice()));
                goodsNum.setText(String.format("x %s", vo.getOrderItems().get(i).getQuantity()));

                activityOrderDetailsLlLayout.addView(goodsLayout);
            }
        }

        orderDetailsTotalGoodsNum.setText("共" + num + "件商品");
        // 商家名称
        orderDetailsSellerName.setText(vo.getSellerName());
        // 商家logo
        FrescoUtil.showImageSmall(vo.getSellerLogo(), orderDetailsSellerLogo);
        // 商家电话
        orderDetailsSellerPhone.setText(vo.getSellerPhone());


        switch (vo.getEqualStatus()) {
            case 10://待提货（已支付 只有自提）
                if(beFrom.equals("buy")){
                    setButtonText("", "获取提货码");
                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CustomDialog.nativeDialog(ShareOrderDetailsActivity.this, "订单提货码：" + vo.getTickCode());
                        }
                    });
                }else{
                    setButtonText("", "验证提货码");
                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new MaterialDialog.Builder(ShareOrderDetailsActivity.this)
                                    .title("提示")
                                    .content("验证提货码")
                                    .inputType(InputType.TYPE_CLASS_NUMBER)
                                    .input("请输入提货码", "", new MaterialDialog.InputCallback() {

                                        @Override
                                        public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                        }
                                    })
                                    .positiveText("确定")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            String verificationCode = dialog.getInputEditText().getText().toString();
                                            if (StringUtil.isStrEmpty(verificationCode)) {
                                                showToast("请输入提货验证码");
                                                return;
                                            }
                                            BusinessShareFarm.pickUpVerification(ShareOrderDetailsActivity.this, vo.getOrderNo(), verificationCode, mHandler);
                                        }
                                    })
                                    .show();

                        }
                    });
                }

                break;
            case 11://待评价 自提
                if(beFrom.equals("buy")){
                    setButtonText("", "评价");
                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GotoUtil.gotoForResultActivity(ShareOrderDetailsActivity.this, EvaluateShareOrderActivity.class, 99, "ShareOrderVO", vo);
                        }
                    });
                }else{
                    setButtonText("", "");
                }

                break;
            case 20://待发货（已支付 只有邮寄）
                if(beFrom.equals("buy")){
                    setButtonText("", "");
                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cancelOrder();
                        }
                    });
                }else{
                    setButtonText("", "确认发货");
                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 使用确认收货方法
                            Intent intent = new Intent(ShareOrderDetailsActivity.this, SelectLogisticsActivity.class);
                            intent.putExtra("ShareOrderVO", vo);
                            startActivityForResult(intent, 99);
                        }
                    });
                }

                break;
            case 21://待收货
                if(beFrom.equals("buy")){
                    setButtonText("查看物流", "确认收货");
                    orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GotoUtil.gotoActivity(ShareOrderDetailsActivity.this, LogisticsQueryActivity.class, "orderNo", vo.getOrderNo());
                        }
                    });

                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new MaterialDialog.Builder(ShareOrderDetailsActivity.this)
                                    .title("提示")
                                    .content("是否确认收货？")
                                    .positiveText("确定")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            BusinessFarmSystem.affirmReceipt(ShareOrderDetailsActivity.this, vo.getOrderNo(), mHandler);
                                        }
                                    })
                                    .show();
                        }
                    });
                }else{
                    setButtonText("", "查看物流");
                    orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GotoUtil.gotoActivity(ShareOrderDetailsActivity.this, LogisticsQueryActivity.class, "orderNo", vo.getOrderNo());
                        }
                    });
                }

                break;
            case 22://待评价 邮寄
                if(beFrom.equals("buy")){
                    setButtonText("", "评价");
                }else{
                    setButtonText("", "");
                }

                orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteOrder();
                    }
                });
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GotoUtil.gotoForResultActivity(ShareOrderDetailsActivity.this, EvaluateShareOrderActivity.class, 99, "ShareOrderVO", vo);
                    }
                });
                break;
            case 19://待支付 自提
                if(beFrom.equals("buy")){
                    setButtonText("取消订单", "支付");
                }else{
                    setButtonText("", "");
                }

                orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder();
                    }
                });
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayVO payVO = new PayVO();
                        payVO.setPrice(vo.getTotalPriceReal() + "");
                        payVO.setOrderNO(vo.getOrderNo());
                        payVO.setType(2);
                        GotoUtil.gotoActivity(ShareOrderDetailsActivity.this, WXPayEntryActivity.class, "payVO", payVO);
                    }
                });
                break;
            case 29://待支付 邮寄
                if(beFrom.equals("buy")){
                    setButtonText("取消订单", "支付");
                }else{
                    setButtonText("", "");
                }

                orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder();
                    }
                });
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayVO payVO = new PayVO();
                        payVO.setPrice(vo.getTotalPriceReal() + "");
                        payVO.setOrderNO(vo.getOrderNo());
                        payVO.setType(2);
                        GotoUtil.gotoActivity(ShareOrderDetailsActivity.this, WXPayEntryActivity.class, "payVO", payVO);
                    }
                });
                break;

            default:
                orderDetailsOrderOperationLayout.setVisibility(View.GONE);
                break;

        }

        // 买家留言
        tvMsg.setText(vo.getTip());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 99 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    /**
     * 删除订单
     */
    private void deleteOrder() {
        new MaterialDialog.Builder(ShareOrderDetailsActivity.this)
                .title("提示")
                .content("是否确认删除该订单？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        BusinessFarmSystem.deleteOrder(ShareOrderDetailsActivity.this, vo.getOrderNo(), mHandler);
                    }
                })
                .show();
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        new MaterialDialog.Builder(ShareOrderDetailsActivity.this)
                .title("提示")
                .content("您确定要取消订单吗？")
                .items(R.array.cancelReason)
                .itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        if (text == null || text == "") {
                            showToast("请选择一个理由！");
                            return true;
                        }
                        BusinessFarmSystem.cancelOrder(ShareOrderDetailsActivity.this, vo.getOrderNo(), text.toString(), mHandler);
                        return true;
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .show();
    }

    /**
     * 设置左右button 如果为空则隐藏button
     *
     * @param leftButtonText
     * @param rightButtonText
     */
    private void setButtonText(String leftButtonText, String rightButtonText) {
        // 左边按钮
        if (StringUtil.isStrEmpty(leftButtonText))
            orderDetailsBtnLeft.setVisibility(View.GONE);
        else
            orderDetailsBtnLeft.setText(leftButtonText);
        // 右边按钮
        if (StringUtil.isStrEmpty(rightButtonText))
            orderDetailsBtnRight.setVisibility(View.GONE);
        else
            orderDetailsBtnRight.setText(rightButtonText);

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_CANCEL_ORDER_AGSRV_SUCCESS:
                        showToast("订单已取消");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_CANCEL_ORDER_AGSRV_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_DELETE_ORDER_AGSRV_SUCCESS:
                        showToast("订单已删除");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_DELETE_ORDER_AGSRV_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_AFFIRM_RECEIPT_SUCCESS:
                        showToast("已确认收货");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_AFFIRM_RECEIPT_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_PICK_UP_VERIFICATION_SUCCESS: // 确认验证码
                        showToast("验证通过");
                        BusinessShareFarm.affirmBuyerPickup(ShareOrderDetailsActivity.this, vo.getOrderNo(), vo.getSellerId(), mHandler);
                        break;
                    case MSG.MSG_PICK_UP_VERIFICATION_FIELD:
                        showToast("验证失败");
                        break;
                    case MSG.MSG_AFFIRM_BUYER_PICKUP_SUCCESS:
                        setResult(RESULT_OK);
                        finish();
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

}
